/**
 * Project Name:mauto-web
 * File Name:ApiAutoConfigController.java
 * Package Name:com.inftech.mauto.sys.web.front
 * Date:2016年10月17日下午9:48:11
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.sys.web.front;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.base.BaseController;
import com.inftech.mauto.common.base.BusinessException;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.common.utils.CommonUtils;
import com.mingsoft.weixin.dao.IWeixinDao;
import com.mingsoft.weixin.entity.WeixinEntity;
import com.mingsoft.weixin.util.JSSDKUtil;

/**
 * ClassName:ApiWeixinController <br/>
 * Function: 微信接口. <br/>
 * Date: 2016年10月17日 下午9:48:11 <br/>
 * 
 * @author puyf
 * @version
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/api/weixin")
public class ApiWeixinController extends BaseController {

	/**
	 * 注入微信持久化层
	 */
	@Autowired
	private IWeixinDao weixinDao;

	/**
	 * 
	 * getSignature:获取签名. <br/>
	 *
	 * @author puyf
	 * @param request
	 * @since JDK 1.7
	 */
	@RequestMapping(value = "/getSignature", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getSignature(@RequestBody String requestStr, HttpServletRequest request) throws Exception {
		String outJson = "";
		try {
			JSONObject jsonObject = (JSONObject) JSONObject.parse(requestStr);
			// 获取微信信息
			WeixinEntity weixin = weixinDao.getEntity(null, null, null);
			JSSDKUtil JSSDKUtil = new JSSDKUtil(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());
			String signature = JSSDKUtil.getSignature(jsonObject.getString("nonceStr"),
					jsonObject.getString("timestamp"), jsonObject.getString("url"));
			if (!CommonUtils.isBlank(signature)) {
				LOG.info("获取JSSDK签名成功");
				// 返回结果
				HttpStatusCodeEnum statusCode = HttpStatusCodeEnum.STATUS_CODE_200;
				outJson = getOutJson(statusCode, true, statusCode.toString(), signature);
			} else {
				throw new Exception();
			}
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				throw e;
			}
			LOG.error("获取JSSDK签名失败", e);
			HttpStatusCodeEnum statusCode = HttpStatusCodeEnum.SCOPE_BASE;
			outJson = getOutJson(statusCode, false, statusCode.toString(), null);
		}
		return outJson;
	}
}
